//
//  AppDelegate.m
//  Conva
//
//  Created by cruise on 2017/12/25.
//  Copyright © 2017年 com.conva. All rights reserved.
//

#import "AppDelegate.h"

#import "AppDelegate+Config.h"

#import "CAHomeViewController.h"
//#import "CALoginViewController.h"
#import "LMNavigationController.h"

#import "LMTabBarViewController.h"
#import <IQKeyboardManager/IQKeyboardManager.h>


#import "LNHConfirmOrderViewController.h"
#import <AlipaySDK/AlipaySDK.h>
#import "CAOrderDoneViewController.h"

NSString *const LMLoginStateChangedNotificationKey = @"LoginStateChangedNotificationKey";

@interface AppDelegate ()

/**
 tabbar控制器
 */
@property (nonatomic, strong) LMTabBarViewController *tabbarController;


/**
 登录控制器
 */
//@property (nonatomic, strong) CALoginViewController *loginController;

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    //键盘注册
    [[self class] setKeyBord];
    // 普通注册
    [self configSVProgressHUD];
    [self configScrollViewAdapt4IOS11];
    [self configNetworkApiEnv];
    
    // 路由注册
    [self registerNavgationRouter];
    [self registerSchemaRouter];
    
    // 配置根视图控制器
    [self setupRootController];
    
    return YES;
}

- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options
{
    if ([url.host containsString:@"safepay"]) {
        // 支付跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"%@", resultDic[@"memo"]);
            NSInteger resultStatus = [resultDic[@"resultStatus"] integerValue];
            if (resultStatus == 9000) {
                //支付成功
                NSString *router = [JLRoutes lm_generateURLWithPattern:LMNavPushRoute parameters:@[NSStringFromClass(CAOrderDoneViewController.class)] extraParameters:nil];
                [[RACScheduler mainThreadScheduler] schedule:^{
                    [[UIApplication sharedApplication] openURL:JLRGenRouteURL(LMDefaultRouteSchema, router) options:nil completionHandler:nil];
                }];
            } else {
                //其他-返回错误信息
                [SVProgressHUD lm_displayErrorWithStatus:resultDic[@"memo"]];
                CAHomeViewController *homeVC = [CAHomeViewController new];
                homeVC.hidesBottomBarWhenPushed = NO;
                homeVC.navigationItem.leftBarButtonItem = [UIBarButtonItem new];
                NSString *router = [JLRoutes lm_generateURLWithPattern:LMNavPushRoute parameters:@[NSStringFromClass(homeVC.class)] extraParameters:nil];
                [[RACScheduler mainThreadScheduler] schedule:^{
                    [[UIApplication sharedApplication] openURL:JLRGenRouteURL(LMDefaultRouteSchema, router) options:nil completionHandler:nil];
                }];
            }
                
        }];
        
        // 授权跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processAuth_V2Result:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
            // 解析 auth code
            NSString *result = resultDic[@"result"];
            NSString *authCode = nil;
            if (result.length>0) {
                NSArray *resultArr = [result componentsSeparatedByString:@"&"];
                for (NSString *subResult in resultArr) {
                    if (subResult.length > 10 && [subResult hasPrefix:@"auth_code="]) {
                        authCode = [subResult substringFromIndex:10];
                        break;
                    }
                }
            }
            NSLog(@"授权结果 authCode = %@", authCode?:@"");
        }];
        return YES;
    }
    // 默认的路由 跳转等等
    else if ([[url scheme] isEqualToString:LMDefaultRouteSchema]) {
        
        return [[JLRoutes globalRoutes] routeURL:url];
    }
    // http
    else if ([[url scheme] isEqualToString:LMHTTPRouteSchema])
    {
        return [[JLRoutes routesForScheme:LMHTTPRouteSchema] routeURL:url];
    }
    // https
    else if ([[url scheme] isEqualToString:LMHTTPsRouteSchema])
    {
        return [[JLRoutes routesForScheme:LMHTTPsRouteSchema] routeURL:url];
    }
    // Web交互请求
    else if ([[url scheme] isEqualToString:LMWebHandlerRouteSchema])
    {
        return [[JLRoutes routesForScheme:LMWebHandlerRouteSchema] routeURL:url];
    }
    // 请求回调
    else if ([[url scheme] isEqualToString:LMComponentsCallBackHandlerRouteSchema])
    {
        return [[JLRoutes routesForScheme:LMComponentsCallBackHandlerRouteSchema] routeURL:url];
    }
    // 未知请求
    else if ([[url scheme] isEqualToString:LMUnknownHandlerRouteSchema])
    {
        return [[JLRoutes routesForScheme:LMUnknownHandlerRouteSchema] routeURL:url];
    }
    return NO;
}

#pragma mark - Engine
/// 初始化根页面
- (void)setupRootController
{
    self.window = [[UIWindow alloc] init];
    self.window.frame = [UIScreen mainScreen].bounds;
    
    //注册通知
    //    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:LMLoginStateChangedNotificationKey object:nil] subscribeNext:^(NSNotification * _Nullable noti) {
    //
    //        NSNumber * number = [[NSUserDefaults standardUserDefaults] objectForKey:@"isLogin"];
    //        BOOL isLogin = YES;
    //        if (number) {
    //            isLogin = number.boolValue;
    //        }
    //        if (isLogin) {//已登录
    
//    LNHConfirmOrderViewController *vc = [[LNHConfirmOrderViewController alloc] init];
//    LMNavigationController *nav = [[LMNavigationController alloc] initWithRootViewController:vc];
//    [self.window setRootViewController:nav];
    [self.window setRootViewController:self.tabbarController];
//            }else//未登录
//            {
//                LMNavigationController *nav = [[LMNavigationController alloc] initWithRootViewController:self.loginController];
//                [self.window setRootViewController:nav];
//            }
//        }];

    // 发送一次通知
    //    [[NSNotificationCenter defaultCenter] postNotificationName:LMLoginStateChangedNotificationKey object:nil];
    
    [self.window makeKeyAndVisible];
}

#pragma mark - Getter
- (LMTabBarViewController *)tabbarController
{
    if (!_tabbarController) {
        _tabbarController = [[LMTabBarViewController alloc] init];
    }
    return _tabbarController;
}

#pragma mark - 键盘回收相关
+ (void) setKeyBord {
    
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    manager.enable = YES;
    manager.shouldResignOnTouchOutside = YES;
    manager.shouldToolbarUsesTextFieldTintColor = NO;
    manager.enableAutoToolbar = NO;
}

//- (CALoginViewController *)loginController
//{
//    if (!_loginController) {
//        _loginController = [[CALoginViewController alloc] init];
//    }
//    return _loginController;
//}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

//- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
//{
//    if ([url.host isEqualToString:@"safepay"]) {
//        // 支付跳转支付宝钱包进行支付，处理支付结果
//        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
//            NSLog(@"result = %@",resultDic);
//        }];
//
//        // 授权跳转支付宝钱包进行支付，处理支付结果
//        [[AlipaySDK defaultService] processAuth_V2Result:url standbyCallback:^(NSDictionary *resultDic) {
//            NSLog(@"result = %@",resultDic);
//            // 解析 auth code
//            NSString *result = resultDic[@"result"];
//            NSString *authCode = nil;
//            if (result.length>0) {
//                NSArray *resultArr = [result componentsSeparatedByString:@"&"];
//                for (NSString *subResult in resultArr) {
//                    if (subResult.length > 10 && [subResult hasPrefix:@"auth_code="]) {
//                        authCode = [subResult substringFromIndex:10];
//                        break;
//                    }
//                }
//            }
//            NSLog(@"授权结果 authCode = %@", authCode?:@"");
//        }];
//    }
//    return YES;
//}
//
//// NOTE: 9.0以后使用新API接口
//- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options
//{
//    if ([url.host isEqualToString:@"safepay"]) {
//        // 支付跳转支付宝钱包进行支付，处理支付结果
//        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
//            NSLog(@"result = %@",resultDic);
//        }];
//
//        // 授权跳转支付宝钱包进行支付，处理支付结果
//        [[AlipaySDK defaultService] processAuth_V2Result:url standbyCallback:^(NSDictionary *resultDic) {
//            NSLog(@"result = %@",resultDic);
//            // 解析 auth code
//            NSString *result = resultDic[@"result"];
//            NSString *authCode = nil;
//            if (result.length>0) {
//                NSArray *resultArr = [result componentsSeparatedByString:@"&"];
//                for (NSString *subResult in resultArr) {
//                    if (subResult.length > 10 && [subResult hasPrefix:@"auth_code="]) {
//                        authCode = [subResult substringFromIndex:10];
//                        break;
//                    }
//                }
//            }
//            NSLog(@"授权结果 authCode = %@", authCode?:@"");
//        }];
//    }
//    return YES;
//}


@end



